const productModel = require('../models/productModel');

// 获取所有商品
async function getAllProducts(req, res) {
    try {
        const products = await productModel.getAllProducts();
        res.json(products);
    } catch (error) {
        res.status(500).json({ error: 'Internal Server Error' });
    }
}

// 根据 ID 获取商品
async function getProductById(req, res) {
    const id = req.params.id;
    try {
        const product = await productModel.getProductById(id);
        if (product) {
            res.json(product);
        } else {
            res.status(404).json({ error: 'Product not found' });
        }
    } catch (error) {
        res.status(500).json({ error: 'Internal Server Error' });
    }
}

// 创建商品
async function createProduct(req, res) {
    const { name, price, description } = req.body;
    try {
        const productId = await productModel.createProduct(name, price, description);
        res.status(201).json({ id: productId, name, price, description });
    } catch (error) {
        res.status(500).json({ error: 'Internal Server Error' });
    }
}

// 更新商品
async function updateProduct(req, res) {
    const id = req.params.id;
    const { name, price, description } = req.body;
    try {
        const affectedRows = await productModel.updateProduct(id, name, price, description);
        if (affectedRows > 0) {
            res.json({ message: 'Product updated successfully' });
        } else {
            res.status(404).json({ error: 'Product not found' });
        }
    } catch (error) {
        res.status(500).json({ error: 'Internal Server Error' });
    }
}

// 删除商品
async function deleteProduct(req, res) {
    const id = req.params.id;
    try {
        const affectedRows = await productModel.deleteProduct(id);
        if (affectedRows > 0) {
            res.json({ message: 'Product deleted successfully' });
        } else {
            res.status(404).json({ error: 'Product not found' });
        }
    } catch (error) {
        res.status(500).json({ error: 'Internal Server Error' });
    }
}

module.exports = {
    getAllProducts,
    getProductById,
    createProduct,
    updateProduct,
    deleteProduct
};